package com.yonyougov.devops.cruxcisupport.k8s.pod;

import com.yonyougov.devops.cruxcisupport.k8s.K8sRepository;
import com.yonyougov.devops.cruxcisupport.k8s.error.K8sConfIgNotFindException;
import com.yonyougov.devops.cruxcisupport.k8s.service.ServiceRepository;
import io.fabric8.kubernetes.api.model.ContainerStatus;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.Service;
import io.fabric8.kubernetes.client.KubernetesClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Repository
public class PodRepositoryImpl implements PodRepository{
    private final K8sRepository k8sRepository;
    private final ServiceRepository serviceRepository;
    public PodRepositoryImpl(K8sRepository k8sRepository, ServiceRepository serviceRepository) {
        this.k8sRepository = k8sRepository;
        this.serviceRepository = serviceRepository;
    }

    @Override
    public Pod get(String nameSpace, String podName) throws K8sConfIgNotFindException {
        KubernetesClient client = k8sRepository.createDefaultClient(nameSpace);
        return get(client,nameSpace,podName);
    }

    @Override
    public Pod get(KubernetesClient client, String nameSpace, String podName) {
        return client.pods().inNamespace(nameSpace).withName(podName).get();
    }

    @Override
    public List<String> getPodNames(String nameSpace, String appName) throws K8sConfIgNotFindException {
        KubernetesClient client = k8sRepository.createDefaultClient(nameSpace);
        return getPodNames(client,nameSpace,appName);
    }

    @Override
    public List<String> getPodNames(KubernetesClient client, String nameSpace, String appName){
        return client.pods().inNamespace(nameSpace).list().getItems()
                .stream()
                .filter(pod -> pod.getMetadata().getName().contains(appName))
                .map(pod -> pod.getMetadata().getName()).collect(Collectors.toList());
    }

    @Override
    public boolean isRunning(String nameSpace, String podName) throws K8sConfIgNotFindException {
        Pod pod = get(nameSpace, podName);
        if(null == pod){
            return false;
        }else{
            List<ContainerStatus> containerStatuses = pod.getStatus().getContainerStatuses();
            if(null != containerStatuses && containerStatuses.size() > 0 ){
                //默认pod里面只有一个容器
                return containerStatuses.get(0).getReady();
            }else{
                return false;
            }
        }
    }

    @Override
    public boolean isRunning(KubernetesClient client, String nameSpace, String podName) {
        Pod pod = get(client,nameSpace, podName);
        if(null == pod){
            return false;
        }else{
            List<ContainerStatus> containerStatuses = pod.getStatus().getContainerStatuses();
            if(null != containerStatuses && containerStatuses.size() > 0 ){
                //默认pod里面只有一个容器
                return containerStatuses.get(0).getReady();
            }else{
                return false;
            }
        }
    }

    @Override
    public List<PodStatusInfo> getAllPodStatusInfo(String nameSpace) throws K8sConfIgNotFindException {
        KubernetesClient client = k8sRepository.createDefaultClient(nameSpace);
        return getAllPodStatusInfo(client,nameSpace);
    }

    @Override
    public List<PodStatusInfo> getAllPodStatusInfo(KubernetesClient client, String nameSpace) {
        List<Pod> podList = client.pods().inNamespace(nameSpace).list().getItems();
        if(null == podList){
            return new ArrayList<PodStatusInfo>();
        }else{
            return podList.stream().map(pod -> {
                PodStatusInfo podStatusInfo = new PodStatusInfo();
                podStatusInfo.setPodName(pod.getMetadata().getName());
                podStatusInfo.setStatus(isRunning(client, nameSpace, pod.getMetadata().getName()) ? "正常" : "不正常");
                podStatusInfo.setVersion(StringUtils.substringAfterLast(pod.getSpec().getContainers().get(0).getImage(), ":"));
                Service service = serviceRepository.getServiceNameByAppName(client, nameSpace, getAppNameByPodName(pod.getMetadata().getName()));
                if (null != service) {
                    podStatusInfo.setServiceName(service.getMetadata().getName());
                } else {
                    podStatusInfo.setServiceName("");
                }
                return podStatusInfo;
            }).collect(Collectors.toList());
        }
    }

    @Override
    public boolean delete(String nameSpace, String podName) throws K8sConfIgNotFindException {
        KubernetesClient client = k8sRepository.createDefaultClient(nameSpace);
        return delete(client,nameSpace,podName);
    }

    @Override
    public boolean delete(KubernetesClient client, String nameSpace, String podName) {
        return client.pods().inNamespace(nameSpace).withName(podName).delete();
    }

    /**
     * 根据Pod名称获取应用名称
     * @param name
     * @return
     */
    private String getAppNameByPodName(String name) {
        StringBuffer sb = new StringBuffer();
        String[] split = StringUtils.split(name,"-");
        for (int i = 0; i <split.length-2 ; i++) {
            if(i == split.length-3){
                sb.append(split[i]);
            }else{
                sb.append(split[i]);
                sb.append("-");
            }
        }
        return sb.toString();
    }
}
